﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SPC
{
    /// <summary>
    /// 单位缺陷（瑕疵）数U控制图
    /// 用于控制缺陷数量
    /// </summary>
    class SpcU : ISPC
    {
        double[] u;//组内不良数量
        double[] ni;
        double ubar;
        double nbar;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="samples">每组检查数量</param>
        /// <param name="NGs">每组不良数量</param>
        public SpcU(double[] samples,double[] bugs)
        {
            u = bugs;
            ni = samples;
            ubar = u.Average();
            nbar = samples.Average();
        }
        public double LSL
        { set { } }
        public double USL
        { set { } }
        public double CP()
        {
            return ubar;
        }

        public double CPK()
        {
            return ubar;
        }

        public SCtrlDiagram[] GetCtrlDiagrams()
        {
            SCtrlDiagram[] diags = new SCtrlDiagram[1];
            diags[0] = new SCtrlDiagram()
            {
                diagramName = DiagramName.u,
                points = u,
                cl = ubar
            };
            double us;
            if (ni.Min() > nbar * 0.25 && ni.Max() < nbar * 0.25)
            {
                us = Math.Sqrt(ubar / nbar);
                double lcl = ubar - 3 * us;
                diags[0].lcl = lcl > 0 ? lcl : 0;
                diags[0].ucl = ubar + 3 * us;
            }
            else
            {
                diags[0].lcls = new double[ni.Length];
                diags[0].ucls = new double[ni.Length];
                for (int i = 0; i < ni.Length; i++)
                {
                    us = Math.Sqrt(ubar / ni[i]);
                    double lcl= ubar - 3 * us;
                    diags[0].lcls[i] = lcl > 0 ? lcl : 0;
                    diags[0].ucls[i] = ubar + 3 * us;
                }
            }
            
            return diags;
        }

        public double PP()
        {
            return ubar;
        }

        public double PPK()
        {
            return ubar;
        }
    }
}
